package org.example.struct.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liyishan
 * @date 2024/2/18 09:18
 * @apiNote
 */

public class Test01624MaxLengthBetweenEqualCharacters {
    public static void main(String[] args) {
        String s = "cabbac";
        System.out.println(maxLengthBetweenEqualCharacters(s));
    }

    public static int maxLengthBetweenEqualCharacters(String s) {
        int ans = -1;
        char[] chars = s.toCharArray();
        Map<Character,Integer> map = new HashMap<>();
        for(char c : chars){
            map.put(c,map.getOrDefault(c,0)+1);
        }
        for(Map.Entry<Character,Integer> entry : map.entrySet()){
            if(entry.getValue() > 1){
                ans = Math.max(ans,s.lastIndexOf(entry.getKey())-s.indexOf(entry.getKey())-1);
            }
        }
        return ans;
    }

    public static int maxLengthBetweenEqualCharacters1(String s) {
        int[] firstIndex = new int[26];
        Arrays.fill(firstIndex, -1);
        int maxLength = -1;
        for(int i = 0; i < s.length(); i++){
            if(firstIndex[s.charAt(i) - 'a'] < 0){
                firstIndex[s.charAt(i) - 'a'] = i;
            }else{
                maxLength = Math.max(maxLength, i - firstIndex[s.charAt(i) - 'a'] - 1);
            }
        }
        return maxLength;
    }
}
